package com.koron.sinoprobe.web.record.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.koron.bean.base.Response;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.business.workflow.util.HttpUtil;
import com.koron.sinoprobe.web.record.bean.SpRecord;
import com.koron.sinoprobe.web.record.bean.SpRecordTree;
import com.koron.sinoprobe.web.record.mapper.SpRecordMapper;
import com.koron.sinoprobe.web.record.service.SpRecordService;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SpRecordServiceImpl implements SpRecordService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String FILE_SYSTEM_KEY = "fileSystem:config";
    public static final String FILE_SYSTEM_CODE = "systemCode";
    public static final String FILE_SYSTEM_PARENTID = "parentID";

    public static final String FILE_SYSTEM_QUERY_TREE_URL = "queryTreeUrl";

    public static final String FILE_SYSTEM_UPLOAD_URL = "uploadUrl";

    private String systemCode;

    private String parentID;

    private String queryTreeUrl;

    private String uploadUrl;

    @PostConstruct
    public void init() {
        getBasicConfig();
    }

    public void getBasicConfig() {

        if (!redisTemplate.hasKey(FILE_SYSTEM_KEY)) {
            Map<String, String> toolMap = ConfigInfoTool.getConfigByCode("system", "fileSystem");
            this.systemCode = toolMap.get(FILE_SYSTEM_CODE);
            this.parentID = toolMap.get(FILE_SYSTEM_PARENTID);
            this.queryTreeUrl = toolMap.get(FILE_SYSTEM_QUERY_TREE_URL);
            this.uploadUrl = toolMap.get(FILE_SYSTEM_UPLOAD_URL);

            if (StrUtil.isAllNotEmpty(this.systemCode, this.parentID, this.queryTreeUrl, this.uploadUrl)){
                redisTemplate.opsForHash().put(FILE_SYSTEM_KEY, FILE_SYSTEM_CODE, systemCode);
                redisTemplate.opsForHash().put(FILE_SYSTEM_KEY, FILE_SYSTEM_PARENTID, parentID);
                redisTemplate.opsForHash().put(FILE_SYSTEM_KEY, FILE_SYSTEM_QUERY_TREE_URL, queryTreeUrl);
                redisTemplate.opsForHash().put(FILE_SYSTEM_KEY, FILE_SYSTEM_UPLOAD_URL, uploadUrl);
                redisTemplate.expire(FILE_SYSTEM_KEY, 1, TimeUnit.DAYS);
            }

        } else {
            Map<Object, Object> map = redisTemplate.opsForHash().entries(FILE_SYSTEM_KEY);
            this.systemCode = (String) map.get(FILE_SYSTEM_CODE);
            this.parentID = (String) map.get(FILE_SYSTEM_PARENTID);
            this.queryTreeUrl = (String) map.get(FILE_SYSTEM_QUERY_TREE_URL);
            this.uploadUrl = (String) map.get(FILE_SYSTEM_UPLOAD_URL);
        }

    }


    @Override
    public Response queryTree() {

        if (StrUtil.isBlank(this.queryTreeUrl)) {
            return Response.fail("请配置档案管理系统查询组织结构url！");
        }

        // 获取文档系统查询树结构url
        //Map<String, String> map = ConfigInfoTool.getConfigByCode("system", "fileSystem");
        //String url = map.get("queryTreeUrl");
        Map<String, Object> param = new HashMap<>();
        param.put(FILE_SYSTEM_CODE, systemCode);
        param.put(FILE_SYSTEM_PARENTID, parentID);
        log.info("systemCode={},parentID={},queryTreeUrl={}", systemCode, parentID, queryTreeUrl);

        String resp = HttpUtil.sendPost(queryTreeUrl, JSON.toJSONString(param));
        JSONObject jsonObject = JSONUtil.parseObj(resp);
        if (jsonObject == null) {
            return Response.fail();
        }
        if (jsonObject.get("code").equals(HttpStatus.OK.value())) {
            List<SpRecordTree> spRecordTreeList = jsonObject.getJSONArray("result").toList(SpRecordTree.class);
            return Response.ok(spRecordTreeList);
        }
        return Response.fail((int) jsonObject.get("code"), (String) jsonObject.get("message"));
    }

    @Override
    public Response upload(SpRecord spRecord) {
        if (Objects.isNull(spRecord)) {
            return Response.fail("文档附件不能为空！");
        }
        if (StrUtil.isBlank(this.uploadUrl)) {
            return Response.fail("请配置档案管理系统上传附件url！");
        }
        log.info("systemCode={},parentID={},uploadUrl={}", systemCode, parentID, uploadUrl);
        spRecord.setSystemCode(systemCode);

        String paramBody = JSON.toJSONString(spRecord);

        String resp = HttpUtil.sendPost(uploadUrl, paramBody);

        JSONObject jsonObject = JSONUtil.parseObj(resp);

        if (jsonObject == null) {
            return Response.fail();
        }

        return jsonObject.get("code").equals(HttpStatus.OK.value()) ? Response.ok() :
                Response.fail((int) jsonObject.get("code"), (String) jsonObject.get("message"));
    }

    @TaskAnnotation("saveFileIndex")
    @Override
    public Response saveFileIndex(SessionFactory factory, String businessId, String indexs) {
        SpRecordMapper mapper = factory.getMapper(SpRecordMapper.class);
        int result = mapper.saveFileIndex(businessId, indexs);
        return result > 0 ? Response.ok(): Response.fail();
    }


    @TaskAnnotation("findFileIndexByBusinessId")
    @Override
    public Response findFileIndexByBusinessId(SessionFactory factory, String businessId) {
        SpRecordMapper mapper = factory.getMapper(SpRecordMapper.class);
        List<Map<String, String>> result = mapper.findFileIndexByBusinessId(businessId);
        return Response.ok(result);
    }
}
